package vn.mobisoft.gachno;

import java.io.IOException;
import java.util.Calendar;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Report extends Activity implements NetworkInterface{
	private ListView list;
	private MyCustomAdapter mAdapter;
	private Vector<Report_item> mData = new Vector<Report_item>();
	
	private Button btn_exit;
	String rawdata = "";
	String total = "";
	
	private int year;
	private int month;
	private int day;
	
	private int page = 1;
	private int step = 300;
	private int totalRecord=-1;
	private int totalMoney=-1;
	
	static final int DATE_DIALOG_ID = 999;
	
	private TextView 	text_total;
	private TextView 	text_date;
	//private DatePicker dpResult;
	
	private static final int 	DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog 		mProgressDialog;
	
	private Function function = new Function();
	private int action;
	protected int selectedItem;
	
    private static final int MENU_XEM_THEO_NGAY = Menu.FIRST;    
    private static final int MENU_SEARCH 		= Menu.FIRST+1;  
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.report);
        
		//Bundle extras = getIntent().getExtras();
		//if (extras != null) {			
		//	rawdata = extras.getString("REPORT_INFOR");
		//	parseInfor(rawdata);
		//}
        
        mAdapter = new MyCustomAdapter(this);  
        list = (ListView)findViewById(R.id.r_listView);
        list.setAdapter(mAdapter);      
        
        list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int pos,
					long arg3) 
			{
				selectedItem = pos;
				final CharSequence[] items = {	"Tên khách hàng: " + mData.elementAt(pos).ten_khachhang, 
												"Mã khách hàng: " + mData.elementAt(pos).ma_tt, 
												"Số đt: " + mData.elementAt(pos).sodt,
												"Số nợ: " + toCurent(mData.elementAt(pos).so_tien) +" vnđ"}; 

				AlertDialog.Builder builder = new AlertDialog.Builder(arg1.getContext());
				builder.setTitle("Thông tin khách hàng");
				builder.setItems(items, null);
				
				builder.setPositiveButton("Thoát", new  android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}
				});
				
				builder.setNegativeButton ("Hủy gạch nợ", new  android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (mData.elementAt(selectedItem).ngay_hien_tai.equals(mData.elementAt(selectedItem).ngay_thanh_toan)) {
							onConnect(CONSTANT.ACTION_HUY_GACH_NO);	
						}else {
							Toast.makeText(getApplicationContext(), "Chỉ hủy được phiếu trong ngày!", Toast.LENGTH_LONG).show();
						}															
					}
				});
				
				AlertDialog alert = builder.create();
				alert.show();

			}
		});
       //mData.add("");
        
        btn_exit = (Button)findViewById(R.id.r_button_exit);
        btn_exit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
        
        text_total = (TextView)findViewById(R.id.r_textView_total);
        text_total.setText(total);


		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		
        text_date = (TextView)findViewById(R.id.r_textView_date);
        //text_date.setText(Function.getDateMonthYear1());
		// set current date into textview
        text_date.setText(new StringBuilder().append(day).append("-").append(month + 1).append("-").append(year).append(" "));		        
        
        onConnect(CONSTANT.ACTION_REPORT);
    }
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_XEM_THEO_NGAY	, 0,"Xem theo ngày").setIcon(android.R.drawable.ic_menu_day);  	
		menu.add(0, MENU_SEARCH	, 0,"Tìm kiếm").setIcon(android.R.drawable.ic_menu_search); 
		return true;
	  }
	  @Override
	  public boolean onOptionsItemSelected(MenuItem item)
	  {   
		  //showMsg(item.getTitle().toString());
		  switch (item.getItemId()) {				
				case MENU_XEM_THEO_NGAY:	
					showDialog(DATE_DIALOG_ID);
					break;
				case MENU_SEARCH:	
	                //set up dialog
	                final Dialog dialog = new Dialog(this);
	                dialog.setContentView(R.layout.search);
	                dialog.setTitle("Tìm kiếm khách hàng");
	                dialog.setCancelable(true);
	                //there are a lot of settings, for dialog, check them all out!
	 
	                //set up text
	                final EditText text_hdid = (EditText) dialog.findViewById(R.id.s_editText_hd_id);
	                final EditText text_dt = (EditText) dialog.findViewById(R.id.s_editText_sodt);
	                //text.setText(R.string.lots_of_text);
	 
	                //set up image view
	 
	                //set up button
	                Button button = (Button) dialog.findViewById(R.id.s_button_search);
	                button.setOnClickListener(new View.OnClickListener() {
	                @Override
	                    public void onClick(View v) {
	                		if (text_hdid.getText().toString().length()<=0 && text_dt.getText().toString().length()<=0) {
	                			Toast.makeText(getApplicationContext(), "Cần nhập thông tin!", Toast.LENGTH_LONG).show();
	                		}else {
	                			onConnect(CONSTANT.ACTION_REPORT_SEARCH, text_hdid.getText().toString(), text_dt.getText().toString());
	                			dialog.dismiss();
	                		}
	                    }
	                });
	                //now that the dialog is set up, it's time to show it    
	                dialog.show();
					break;
		  }
		  return super.onOptionsItemSelected(item);
	  }
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// set date picker as current date
			//onConnect(CONSTANT.ACTION_REPORT, Function.getddMMyy());
			return new DatePickerDialog(this, datePickerListener, year, month, day);			
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setTitle("");
			mProgressDialog.setMessage("Xin chờ trong giây lát!");
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into textview
			//text_date.setText(new StringBuilder().append(month + 1).append("-").append(day).append("-").append(year).append(" "));
			text_date.setText(new StringBuilder().append(day).append("-").append(month + 1).append("-").append(year).append(" "));
			mData.clear();
			mAdapter.notifyDataSetChanged();
			onConnect(CONSTANT.ACTION_REPORT, Function.getddMMyy(day, month, year));
			// set selected date into datepicker also
			//dpResult.init(year, month, day, null);

			//Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
			
			//lgThread = new LoginAsync();
			//lgThread.execute();
		}

	};


	
    private class MyCustomAdapter extends BaseAdapter {
        private LayoutInflater 		mInflater;
        private Context activity;
        
        public MyCustomAdapter(Context a) {
        	activity = a;
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        
        public int getCount() {
            return mData.size();
        }
 
        public Report_item getItem(int position) {
            return mData.get(position);
        }
 
        public long getItemId(int position) {
            return position;
        }
 
		@Override
		public View getView(final int pos, View convertView, ViewGroup parent) {       	
    		convertView = mInflater.inflate(R.layout.report_item, null);  
    	
    		
    		TextView name = (TextView)convertView.findViewById(R.id.ri_textView_name);
    		name.setText((pos+1)+": "+mData.elementAt(pos).ten_khachhang);
    		
    		TextView address = (TextView)convertView.findViewById(R.id.ri_textView_infor);
    		address.setText("Mã kh: "+mData.elementAt(pos).ma_tt);
    		
    		TextView money = (TextView)convertView.findViewById(R.id.ri_textView_money);
    		money.setText("Tổng:" +toCurent(mData.elementAt(pos).so_tien) +" vnđ");
    		
            return convertView;
		}
    }
    public String toCurent(String s) {
		int m= Integer.parseInt(s);
		return String.format("%,d",m);
    }
    
    public void onConnect(int connectType, String... arg) {
    	action = connectType;
    	String link = "";
    	switch (connectType) {
    	
		case CONSTANT.ACTION_REPORT:
			if (arg.length>0) {
				link = String.format(CONSTANT.LINK_REPORT, ((Global)getApplication()).getMid(), page+"", step+"", arg[0], ((Global)getApplication()).getCode());
			}else link = String.format(CONSTANT.LINK_REPORT, ((Global)getApplication()).getMid(), page+"", step+"", Function.getDateMonthYear1(), ((Global)getApplication()).getCode());
			break;
		case CONSTANT.ACTION_HUY_GACH_NO:			
			link = String.format(CONSTANT.LINK_HUY_GACHNO, mData.elementAt(selectedItem).phieutra, mData.elementAt(selectedItem).nguoigachid);
			break;		 
		case CONSTANT.ACTION_REPORT_SEARCH:			
			link = String.format(CONSTANT.LINK_REPORT_SEARCH, ((Global)getApplication()).getMid(), arg[0], arg[1]);
			break;		
		} 	
    	Network network = new Network();
    	network.onConnectListener(this);
    	network.execute(link);
    }
    
    
	@Override
	public void startNetworkConnect() {
		showDialog(DIALOG_DOWNLOAD_PROGRESS);		
	}

	@Override
	public void networkProgressUpdate(String... progress) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stopNetworkConnect(String result) {
		System.out.println(result);
		dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
		if (result==null) {
			return;
		}
		result = result.trim();
		switch (action) {
		case CONSTANT.ACTION_REPORT:
			//cap nhat report
			if (page==1) {
				String s[] = result.split("<br/>");
				if (s.length>1) { 
					try {
						totalRecord = Integer.parseInt(s[0]);
						totalMoney  = Integer.parseInt(s[1].substring(s[1].indexOf(":")+1));
					} catch (NumberFormatException e) {
						totalRecord = 0;
						totalMoney = 0;
						e.printStackTrace();
					}
					text_total.setText(totalRecord +" phiếu  "+toCurent(totalMoney+"")+" vnđ");
				} 				
			}
			
			mData = function.parseReportList(result);
			mAdapter.notifyDataSetChanged();
			//updateAutoCompleteText();
			break;
		case CONSTANT.ACTION_HUY_GACH_NO:	
			if (result.equals("1")) {
				Toast.makeText(getApplicationContext(), "Hủy phiếu thành công!", Toast.LENGTH_LONG).show();
				updateList();
			}else {
				Toast.makeText(getApplicationContext(), "Hủy thất bại!", Toast.LENGTH_LONG).show();
			}
			break;
		case CONSTANT.ACTION_REPORT_SEARCH:	
			String[] arr = result.split(":");
			if (arr.length>=8) {
				Report_item ri = new Report_item(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7]);
			
			
				final CharSequence[] items = {	"Tên khách hàng: " + ri.ten_khachhang, 
						"Mã kh: " + ri.ma_tt, 
						"Số đt: " + ri.sodt,
						"Số nợ: " + toCurent(ri.so_tien) +" vnđ"}; 
	
				AlertDialog.Builder builder = new AlertDialog.Builder(
						this);
				builder.setTitle("Thông tin khách hàng");
				builder.setItems(items, null);
	
				builder.setPositiveButton("Thoát",
						new android.content.DialogInterface.OnClickListener() {
	
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
	
							}
						});
	
				builder.setNegativeButton("Hủy gạch nợ",
						new android.content.DialogInterface.OnClickListener() {
	
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (mData.elementAt(selectedItem).ngay_hien_tai
										.equals(mData.elementAt(selectedItem).ngay_thanh_toan)) {
									onConnect(CONSTANT.ACTION_HUY_GACH_NO);
								} else {
									Toast.makeText(getApplicationContext(),
											"Chỉ hủy được phiếu trong ngày!",
											Toast.LENGTH_LONG).show();
								}
							}
						});
	
				AlertDialog alert = builder.create();
				alert.show();
			}
			break;
		}
	}

	private void updateList() {
		//mData.clear();
		onConnect(CONSTANT.ACTION_REPORT);
		//mData.removeElementAt(selectedItem);
		//mAdapter.notifyDataSetChanged();
	}

	@Override
	public void networkError(IOException e) {
		// TODO Auto-generated method stub
		
	}	

}
